package at.markusreich.racecalendar.client;

import at.markusreich.racecalendar.client.presenter.CalendarPresenter;
import at.markusreich.racecalendar.client.presenter.Presenter;
import at.markusreich.racecalendar.client.service.CalendarServiceAsync;
import at.markusreich.racecalendar.client.view.CalendarWidget;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.RootPanel;

public class AppController implements ValueChangeHandler<String> {
	private final HandlerManager eventBus;
	private final CalendarServiceAsync calendarService;
	private HasWidgets mainContainer;

	public AppController(CalendarServiceAsync calendarService, HandlerManager eventBus) {
		this.eventBus = eventBus;
		this.calendarService = calendarService;
		bind();
	}

	private void bind() {
	    History.addValueChangeHandler(this);

//	    eventBus.addHandler(AddContactEvent.TYPE,
//	        new AddContactEventHandler() {
//	          public void onAddContact(AddContactEvent event) {
//	            doAddNewContact();
//	          }
//	        });

	  }

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
	    String token = event.getValue();

	    if (token != null) {
	      Presenter presenter = null;

	      if (token.equals("list")) {
	        presenter = new CalendarPresenter(calendarService, eventBus, new CalendarWidget());
	      }
//	      else if (token.equals("add")) {
//	        presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView());
//	      }
//	      else if (token.equals("edit")) {
//	        presenter = new EditContactPresenter(rpcService, eventBus, new EditContactView());
//	      }

	      if (presenter != null) {
	        presenter.go(mainContainer);
	      }
	    }
	  }

	public void go(RootPanel rootPanel) {
		this.mainContainer = rootPanel.get("mainContainer");

	    if ("".equals(History.getToken())) {
	      History.newItem("list");
	    }
	    else {
	      History.fireCurrentHistoryState();
	    }
	}

}
